package com.itboye.ihomebank.activity.keytwo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.bigkoo.pickerview.TimePickerView;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.key.UpdateKeyTimeActivity;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.KaiSuoJiLu;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.KeyTwoPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 钥匙授权管理
 */
public class KeyShouQuanActivity extends BaseOtherActivity implements Observer {
    View v_statusbar;
    TextView save;
    ImageView close_icon;
    TextView add_shap_title_tv;
    TextView dongjie, delete;
    ImageView key_title_shezhi;//下拉的那个框
    EditText edit_name;
    private String lockId;//锁id
    private String keyId;//钥匙id
    private String toUid;//钥匙的用户id
    private String status;//锁状态
    private String type;//1代表授权
    private String start;//开始时间
    private String end;//结束时间
    private String uid;

    private List<KaiSuoJiLu.KaiSuoJiLuList> beans = new ArrayList<>();
    KeyTwoPresenter keyPresenter;

    TextView start_time, end_time, update_ok;
    private TimePickerView pvCustomTimeStart, pvCustomTimeEnd;
    long startT, endT;
    long currentTime;
    String sid;
    int cz;
    @Override
    protected int layout_id() {
        return R.layout.activity_key_shou_quan;
    }

    @Override
    protected void onInitController() {

    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("钥匙权限管理");
        save.setVisibility(View.VISIBLE);
        initTimePickerStart();
        initTimePickerEnd();
        keyPresenter = new KeyTwoPresenter(this);
        lockId = getIntent().getStringExtra("lockid");
        keyId = getIntent().getStringExtra("keyid");
        toUid = getIntent().getStringExtra("touid");
        status = getIntent().getStringExtra("status");
        start = getIntent().getStringExtra("start");
        end = getIntent().getStringExtra("end");
        startT = Long.parseLong(start);
        endT = Long.parseLong(end);
        if (start.equals("0")) {
            start_time.setText("");
            end_time.setText("");
        } else {
            start_time.setText(TimesUtils.timeStamp2Date(Long.parseLong(start)));
            end_time.setText(TimesUtils.timeStamp2Date(Long.parseLong(end)));
        }

        if (status.equals("110405")) {
            dongjie.setText("解冻");
        } else {
            dongjie.setText("冻结");
        }

        uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
    }

    protected void onReadIntent(Bundle bundle) {

    }

    String alias;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.key_title_xuan:
            case R.id.key_title_xuanze:
                Intent intent = new Intent(KeyShouQuanActivity.this, UpdateKeyTimeActivity.class);
                intent.putExtra("lockid", lockId);
                intent.putExtra("keyid", keyId);
                intent.putExtra("start", start);
                intent.putExtra("end", end);
                startActivity(intent);
                break;
            case R.id.dongjie:// 冻结，解冻
                showProgressDialog("修改中,请稍后......", true);
                sid= SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                cz=1;
                if ("".equals(sid)){
                    if (dongjie.getText().toString().equals("冻结")) {
                        keyPresenter.onDongJie(uid, toUid, lockId, keyId);
                    } else {
                        keyPresenter.onJieDong(uid, toUid, lockId, keyId);
                    }

                }else {
                    if (dongjie.getText().toString().equals("冻结")) {
                        keyPresenter.onDongJie(sid, toUid, lockId, keyId);
                    } else {
                        keyPresenter.onJieDong(sid, toUid, lockId, keyId);
                    }

                }

                break;
            case R.id.delete:// 删除
                showProgressDialog("删除中,请稍后......", true);
                sid= SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                cz=2;
                if ("".equals(sid)){
                    keyPresenter.onUnbindLock(uid, "", keyId, "");

                }else {
                    keyPresenter.onUnbindLock(sid, "", keyId, "");

                }
                break;
            case R.id.update_ok:
                if (String.valueOf(startT).equals(start) && String.valueOf(endT).equals(end)) {
                    ByAlert.alert("未做更改");
                    return;
                }
                if (endT <= startT) {
                    ByAlert.alert("结束时间应该大于开始时间");
                    return;
                }
                if (currentTime > endT) {
                    ByAlert.alert("结束时间应该大于当前时间");
                    return;
                }
                showProgressDialog("请稍后...", true);
                cz=3;
                sid= SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                if ("".equals(sid)){
                    keyPresenter.onYouXiaoQi(uid, keyId, lockId, startT + "", endT + "");

                }else {
                    keyPresenter.onYouXiaoQi(sid, keyId, lockId, startT + "", endT + "");

                }

                break;
            case R.id.start_time:
            case R.id.kaishi_time:
                pvCustomTimeStart.show();
                break;
            case R.id.end_time:
            case R.id.jieshu_time:
                pvCustomTimeEnd.show();
                break;
            case R.id.save:
//                if (alias.equals(edit_name.getText().toString())) {
//                    ByAlert.alert("当前没有做修改");
//                    return;
//                }
                alias = edit_name.getText().toString();
                if (alias.equals("")) {
                    ByAlert.alert("请输入钥匙名字");
                    return;
                }
                showProgressDialog("正在修改，请稍后......", false);
                cz=4;
                sid= SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
                if ("".equals(sid)){
                    keyPresenter.onEditkey(uid, keyId, alias);
                }else {
                    keyPresenter.onEditkey(sid, keyId, alias);
                }

                break;
            default:
                break;
        }

    }

    @Override
    public void update(Observable o, Object data) {
        ResultEntity entity = handlerError(data);
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
        if (entity != null) {
            //冻结
            if (entity.getEventType() == KeyTwoPresenter.dongjie_success) {
                ByAlert.alert(entity.getData());
                dongjie.setText("解冻");
            } else if (entity.getEventType() == KeyTwoPresenter.dongjie_fail) {
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getData());
                }
            } else if (entity.getEventType() == KeyTwoPresenter.jiedong_success) { //解冻
                ByAlert.alert(entity.getData());
                dongjie.setText("冻结");
            } else if (entity.getEventType() == KeyTwoPresenter.jiedong_fail) {
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getData());
                }
            } else if (entity.getEventType() == KeyTwoPresenter.unbindAdmin_success) {  //删除
                ByAlert.alert(entity.getData());
                finish();
            } else if (entity.getEventType() == KeyTwoPresenter.unbindAdmin_fail) {
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getData());
                }
            } else if (entity.getEventType() == KeyTwoPresenter.qixian_success) {
                ByAlert.alert(entity.getData());
                finish();
            } else if (entity.getEventType() == KeyTwoPresenter.qixian_fail) {
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getData());
                }
            }else if (entity.getEventType() == KeyTwoPresenter.key_alias_success) {
                ByAlert.alert(entity.getData());
                finish();
            } else if (entity.getEventType() == KeyTwoPresenter.key_alias_fail) {
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getData());
                }
            }else if (entity.getEventType()== UserPresenter.By_GETSID_success){//获取sid 成功
                SIDBean data1 = (SIDBean) entity.getData();
                SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                toRefreshData(data1.getSid());
            }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                ByAlert.alert(entity.getMsg());
            }
        }
    }

    private void toRefreshData(String sid) {
        if (cz==1){
            if ("".equals(sid)){
                if (dongjie.getText().toString().equals("冻结")) {
                    keyPresenter.onDongJie(uid, toUid, lockId, keyId);
                } else {
                    keyPresenter.onJieDong(uid, toUid, lockId, keyId);
                }

            }else {
                if (dongjie.getText().toString().equals("冻结")) {
                    keyPresenter.onDongJie(sid, toUid, lockId, keyId);
                } else {
                    keyPresenter.onJieDong(sid, toUid, lockId, keyId);
                }

            }
        }else if (cz==2){
            if ("".equals(sid)){
                keyPresenter.onUnbindLock(uid, "", keyId, "");

            }else {
                keyPresenter.onUnbindLock(sid, "", keyId, "");

            }
        }else if (cz==3){
            if ("".equals(sid)){
                keyPresenter.onYouXiaoQi(uid, keyId, lockId, startT + "", endT + "");

            }else {
                keyPresenter.onYouXiaoQi(sid, keyId, lockId, startT + "", endT + "");

            }
        }else if (cz==4){
            sid= SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";
            if ("".equals(sid)){
                keyPresenter.onEditkey(uid, keyId, alias);
            }else {
                keyPresenter.onEditkey(sid, keyId, alias);
            }
        }

    }
    private void initTimePickerStart() {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2017, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTimeStart = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                start_time.setText(getTime(date));
                startT = TimesUtils.getStringToDateTwo02(getTime(date)) / 1000;
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)

                .setType(new boolean[]{true, true, true, true, false, false})
                .setLabel("年", "月", "日", "时", "", "")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFF24AD9D)
                .build();
    }

    private void initTimePickerEnd() {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2017, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTimeEnd = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                end_time.setText(getTime(date));
                endT = TimesUtils.getStringToDateTwo02(getTime(date)) / 1000;
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)

                .setType(new boolean[]{true, true, true, true, false, false})
                .setLabel("年", "月", "日", "时", "", "")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFF24AD9D)
                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        return format.format(date);
    }
}
